package zy.service.report.excel.config;

import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

public class BeanWriter<T> extends AbstractFormatWriter<T> {
	private Class<T> clazz;

	public BeanWriter(Class<T> clazz) {
		this.clazz = clazz;
	}

	@Override
	public void writeTitle(Sheet sheet, String title, String[] label, String[] name, List<T> data) {
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, label.length - 1));
		Row row = sheet.createRow(0);
		Cell titleCell = row.createCell(0);
		titleCell.setCellType(CellType.STRING);
		titleCell.setCellValue(title);
	}

	@Override
	public void writeHead(Sheet sheet, String title, String[] label, String[] name, List<T> data) {
		Row headRow = sheet.createRow(1);
		int length = label.length;
		for (int j = 0; j < length; j++) {
			Cell tempCell = headRow.createCell(j);
			tempCell.setCellType(CellType.STRING);
			tempCell.setCellValue(label[j]);
		}
	}

	@Override
	public void writeData(Sheet sheet, String title, String[] label, String[] name, List<T> data) {
		try {
			int size = data.size();
			for (int j = 0; j < size; j++) {
				Row dataRow = sheet.createRow(2 + j);
				T rowData = data.get(j);

				boolean _defaultRowCallback = true;
				for (RowCallback<T> rowCallback : rowCallbacks) {
					if (rowCallback.canProcess(j, rowData, dataRow)) {
						rowCallback.process(j, rowData, dataRow);
						_defaultRowCallback = false;
						break;
					}
				}

				if (_defaultRowCallback) {
					int column = name.length;
					for (int k = 0; k < column; k++) {
						Cell tempCell = dataRow.createCell(k);
						String columnName = name[k];
						Object value = clazz.getMethod("get" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1)).invoke(rowData);

						boolean _defaultColumnCallback = true;
						for (ColumnCallback<T> columnCallback : columnCallbacks) {
							if (columnCallback.canProcess(j, rowData, dataRow, k, value, columnName, tempCell)) {
								columnCallback.process(j, rowData, dataRow, k, value, columnName, tempCell);
								_defaultColumnCallback = false;
								break;
							}
						}

						if (_defaultColumnCallback) {
							if (value != null) {
								tempCell.setCellType(CellType.STRING);
								tempCell.setCellValue(value.toString());
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("反射获取值失败", e);
		}
	}
}